import useAuthStore from "~/stores/authStore";
export default defineNuxtRouteMiddleware((to, from) => {

    if (import.meta.server) return

    const login = () => {
        const authStore = useAuthStore();
        const token = localStorage.getItem('token');
        const isAdmin = localStorage.getItem('isAdmin');
        if (token) {
            authStore.login(token, JSON.parse(isAdmin || 'false'))
        }
        return authStore
    }

    const authStore= login()


    if (to.path === '/cabinet' && !authStore.isAuth) {
        return navigateTo('/login')
    }

    if (to.path === '/cabinet' && authStore.isAdmin) {
        return navigateTo('/admin')
    }

    if ((to.path === '/admin' || to.path === '/create' || to.name === 'tour-id-edit' || to.name === 'tour-id-users') && !authStore.isAdmin) {
        return navigateTo('/cabinet')
    }

    if ((to.path === '/login' || to.path === '/register') && authStore.isAuth) {
        return navigateTo('/cabinet')
    }
})